import 'dart:async';

import 'package:flutter/material.dart';
import 'package:yuan_hang_app/base/base_page.dart';
import 'package:yuan_hang_app/base/base_state.dart';
import 'package:yuan_hang_app/base/full_base_page.dart';
import 'package:yuan_hang_app/bean/version_entity.dart';
import 'package:yuan_hang_app/http/api.dart';
import 'package:yuan_hang_app/http/http_utils.dart';
import 'package:yuan_hang_app/res/w_colors.dart';
import 'package:yuan_hang_app/res/w_constant.dart';
import 'package:yuan_hang_app/res/w_dimens.dart';
import 'package:yuan_hang_app/utils/common_utils.dart';
import 'package:yuan_hang_app/utils/router_helper.dart';
import 'package:yuan_hang_app/utils/size_utils.dart';
import 'package:yuan_hang_app/utils/string_utils.dart';
import 'package:yuan_hang_app/utils/common_req_utils.dart';
import 'package:yuan_hang_app/views/home/model/order_manager_model.dart';
import 'package:yuan_hang_app/views/home/view/order/order_detail_page.dart';
import 'package:yuan_hang_app/views/home/view/order/order_edit_page.dart';
import 'package:yuan_hang_app/widget/common_dialog.dart';

import 'package:yuan_hang_app/widget/custom_search.dart';
import 'package:yuan_hang_app/widget/custom_tab.dart';
import 'package:yuan_hang_app/widget/sort_content.dart';
import 'package:yuan_hang_app/widget/status_btn.dart';
import 'package:yuan_hang_app/widget/w_line.dart';
import 'package:yuan_hang_app/widget/w_list_view.dart';
import 'package:yuan_hang_app/widget/w_popup_window.dart';
import 'package:yuan_hang_app/widget/w_text.dart';

///下单管理
class OrderManagerPage extends StatefulWidget {
  const OrderManagerPage({super.key});

  @override
  BaseState<OrderManagerPage> createState() => _OrderManagerPageState();
}

class _OrderManagerPageState extends BaseState<OrderManagerPage> {
  List<Map> tabList =
      CommonReqUtils.getLabelListByKey(CommonReqUtils.orderStatus);
  List<Map> versionList = [];
  List currentOrderList = [];

  WListViewState? listState;

  String modelId = "";
  Map sortParams = {};

  Map<String, dynamic> queryParams = {
    "pageNum": 1,
    "limit": 20,
  };

  @override
  FullBasePage buildState(BuildContext context) {
    return FullBasePage(
      title: "代客下单",
      // rightWidget: GestureDetector(
      //   onTap: () {
      //
      //   },
      //   child: WText(
      //     "代客下单",
      //     style: TextStyle(
      //         color: WColors.mainTextColor, fontSize: WDimens.tsMedium),
      //   ),
      // ),
      child: Column(
        children: [
          CustomSearch(
            hintText: "订单编号/客户名称/手机号码",
            //    showSort: false,
            onTextChange: (text) {
              queryParams["queryParam"] = text;
              queryParams["pageNum"] = 1;
              showLoading();
              CommonUtils.antiShake(getOrderList);
            },
            onSortClick: () {
              WPopupWindow.showSort(
                  context: context,
                  sortType: SortType.ORDER_MANAGER,
                  sortParams: sortParams,
                  isScrollControlled: false,
                  onSelected: (params) {
                    sortParams = params;
                    print("params$params");
                    params.forEach((key, value) {
                      queryParams[key] = value;
                      if (queryParams.containsKey(key) && value == null) {
                        queryParams.remove(key);
                      }
                    });
                    showLoading();
                    getOrderList();
                  });
            },
          ),
          CustomTab(
            tabList: tabList,
            titleKey: "label",
            tabClick: (index) {
              queryParams["pageNum"] = 1;
              queryParams["orderStatus"] =
                  index == 0 ? "" : tabList[index]["value"];
              showLoading();
              getOrderList();
            },
          ),
          Expanded(
              child: WListView(
            itemBuilder: _orderItem,
            padding: EdgeInsets.symmetric(vertical: 10.px),
            getDataList: (currentState, page) {
              listState = currentState;
              queryParams["pageNum"] = page;
              getOrderList();
            },
          )),
          GestureDetector(
            onTap: () {
              RouteHelper.pushWidget(context, OrderEditPage());
            },
            child: Container(
              margin: EdgeInsets.symmetric(vertical: 16.px, horizontal: 10.px),
              width: SizeUtils.screenW() - 48.px,
              alignment: Alignment.center,
              height: 48.px,
              decoration: BoxDecoration(
                color: WColors.primaryColor,
                borderRadius: BorderRadius.circular(24.px),
              ),
              child: WText(
                "代客下单",
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 16.px,
                ),
              ),
            ),
          )
        ],
      ),
    );
  }

  @override
  void initState() {
    super.initState();
    tabList.insert(0, {"value": "0", "label": "全部"});
  }

  void getOrderList() {
    HttpUtils().post(Api.getOrderList, data: queryParams).then((data) {
      hideLoading();
      if (data.resultCode == 200) {
        listState?.onRefreshData(
            data.data["records"] ?? [], queryParams["pageNum"]);
      } else if (data.resultCode == 500) {
        listState?.onFail(data.errMsg);
      }
    }).catchError((e) {
      hideLoading();
    });
  }

  // void getVersionByModeId() {
  //   CommonReqUtils.getVersionByModeId(modelId).then((value) {
  //     versionList = VersionEntity.exchangeLabelList(value);
  //   });
  // }
  Widget _orderItem(context, index, list) {
    Map item = list[index];
    item["status"] = CommonReqUtils.exchangeCodeToName2(
            WConstant.orderStatusList, item["orderStatus"]) ??
        "";

    Color statusColor = orderManagerModel.exchangeStatus(item["status"]);
    return GestureDetector(
      onTap: () {
        if (item["status"] == "已取消" || item["status"] == "已下定") {
          RouteHelper.pushWidget(context, const OrderDetailPage());
        } else {
          RouteHelper.pushWidget(
              context,
              OrderEditPage(
                orderId: item["id"],
              )).then((value) {
            if (value != null && value) {
              queryParams["pageNum"] = 1;
              showLoading();
              getOrderList();
            }
          });
        }
      },
      child: Container(
        margin: EdgeInsets.only(left: 15.px, right: 15.px, bottom: 10.px),
        padding: EdgeInsets.only(top: 10.px, right: 10.px, bottom: 5.px),
        decoration: BoxDecoration(
            color: WColors.white, borderRadius: BorderRadius.circular(10.px)),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                WLine(
                  marginRight: 10.px,
                  height: 16.px,
                  width: 4.px,
                  color: WColors.primaryColor,
                ),
                Expanded(
                  child: WText(
                    StringUtils.safeGetValue(item["orderNo"]),
                    style: TextStyle(
                        color: WColors.mainTextColor,
                        fontSize: WDimens.tsLarge,
                        fontWeight: FontWeight.bold),
                  ),
                ),
                StatusBtn(
                  text: item["status"],
                  color: statusColor,
                  isItemBtn: true,
                  isTag: true,
                  height: 28.px,
                  width: 60.px,
                  onPressed: () {},
                )
              ],
            ),
            WLine(
              height: 0.5.px,
              marginTop: 5.px,
              marginBottom: 5.px,
              marginLeft: 10.px,
            ),
            Padding(
              padding: EdgeInsets.only(left: 10.px),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    children: [
                      WText(
                        "${StringUtils.safeGetValue(item["customerName"])}${item["sex"] == 10021001 ? "先生" : "女士"}",
                        style: TextStyle(
                            color: WColors.mainTextColor,
                            fontSize: WDimens.tsMedium),
                      ),
                      SizedBox(
                        width: 5.px,
                      ),
                      WText(
                        StringUtils.safeGetValue(item["mobile"]),
                        style: TextStyle(
                            color: WColors.mainTextColor,
                            fontSize: WDimens.tsMedium),
                      ),
                    ],
                  ),
                  SizedBox(
                    height: 5.px,
                  ),
                  WText(
                      "${StringUtils.safeGetValue(item["modelName"])} "
                      "${StringUtils.safeGetValue(item["versionName"])}",
                      style: TextStyle(
                          color: WColors.subTextColor,
                          fontSize: WDimens.tsMedium)),
                  SizedBox(
                    height: 5.px,
                  ),
                  WText(
                    StringUtils.safeGetValue(item["createdAt"]),
                    textAlign: TextAlign.right,
                    style: TextStyle(
                      color: WColors.hintTextColor,
                      fontSize: WDimens.tsMedium,
                    ),
                  ),
                ],
              ),
            ),
            Offstage(
              offstage: item["status"] != "已保存",
              child: WLine(
                height: 0.5.px,
                marginTop: 5.px,
                marginBottom: 5.px,
                marginLeft: 10.px,
              ),
            ),
            Offstage(
                offstage: item["status"] != "已保存",
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    StatusBtn(
                      isItemBtn: true,
                      height: 28.px,
                      paddingHorizontal: 5.px,
                      text: "收取定金",
                      color: WColors.primaryColor,
                      onPressed: () {
                        CommonDialog.showEWDialog(context: context, url: "收取定金");
                      },
                    )
                  ],
                ))
          ],
        ),
      ),
    );
  }
}
